package org.xxpay.pay.channel.guanghui.utils;

import com.alibaba.fastjson.JSON;
import org.xxpay.common.bean.result.PayException;
import org.xxpay.common.exception.PayErrorException;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.pay.channel.guanghui.GhpayConfig;

import java.net.URLEncoder;
import java.util.Map;

public class GhSignUtils {

    protected static final MyLog _log = MyLog.getLog(GhSignUtils.class);

    private final static String logPrefix = "【广汇付】";

    /**
     * 签名生成
     * @param parameters
     * @return
     */
    public static String setSign(Map<String, Object> parameters, GhpayConfig config) {
        String signTxt = SignUtils.parameterText(parameters);
        String sign = SignUtils.MD5.createSign(signTxt, config.getPrivateKey(), SignUtils.CHARSET_UTF8);
        _log.info("{}签名字符串：{}， 签名：{}",logPrefix, signTxt, sign);
        return sign;
    }

    /**
     * 加密参数
     * @return
     */
    public static String getEncryptionDate (Map<String, Object> busMap,GhpayConfig config) {
        String businessData = JSON.toJSONString(busMap);
        _log.info("{}请求业务数据：{}", logPrefix, businessData);
        /**
         * 业务数据des加密
         */
        try {
            businessData = DesUtils.encrypt(businessData,config.getPublicKey());
        } catch (Exception e) {
            throw new PayErrorException(new PayException("Invalid Arguments", "广汇付业务参数加密失败"));
        }
        /**
         * 加密结果 UrlEncode
         */
        businessData = URLEncoder.encode(businessData);

        return businessData;
    }
}
